using System.Web.Services;
using System.Xml;
using System;

namespace umlungu.engineX.pop3X {
	/// <summary>
	/// umlungu Gatekeeper. 
	/// Validation of users for access to engineX internet-based services is managed from within the Gatekeeper.
	/// </summary>
	[WebService(Namespace="http://www.umlungu.com/engineX/")]
	public class pop3X : x_result
	{
		/// <summary>
		/// Local objects to access internal methods
		/// </summary>
		private x_pop3 pop;
		
		#region Private methods
		private void connect(string host, string user, string password) {
			pop = new x_pop3(host, user, password);
			pop.Connect();
			pop.Login();
		}
		private void quit() {
			pop.Logout();
		}
		#endregion

		#region Protected methods
		/// <summary>Constructor</summary>
		public pop3X() : base("pop3X") {
		}
		#endregion

		#region General web service methods
		
		/// <summary>
		/// Gets the list of emails (and sizes) from email server
		/// </summary>
		[WebMethod] public XmlDocument ListMessages(string Host, string Username, string Password) {
			try {
				connect(Host, Username, Password);
				_AddOk();
				char[] sep = {'\n'}, sepln = {' '};
				string[] msgln, msgs = pop.List().Split(sep);
				for(int i=1; i<msgs.Length-1; i++) {
					msgln = msgs[i].Split(sepln);
					_Add("message", msgln[0], "length", msgln[1]);
				}
				quit();
			} 
			catch(x_exception e)		{_AddError(e);}
			catch(System.Exception e) 	{_AddError(e);}
			return(Result);
		}

		/// <summary>
		/// Counts emails on email server
		/// </summary>
		[WebMethod]
		public int CountMessages(string Host, string Username, string Password) {
			int retval = -1;
			//try {
				connect(Host, Username, Password);
				char[] sep = { '\n' };
				string[] msgs = pop.List().Split(sep);
				retval = msgs.Length-2;
				quit();
			//}
			//catch { }
			return retval;
		}

		/// <summary>
		/// Gets an email from email server
		/// </summary>
		[WebMethod] public XmlDocument GetMessage(string Host, string Username, string Password, int email) {
			try {
				connect(Host, Username, Password);
				_AddOk();
				x_pop3msg popmsg = new x_pop3msg(pop.Retrieve(email));
				_AddText("message", popmsg.ToString());
				/*
				char[] sep = {'\r'}, sepln = {' '};
				string[] msgs = pop.Retrieve(email).Split(sep);
				for(int i=1; i<msgs.Length-1; i++) {
					_AddText("message", msgs[i]);
				}
				*/
				quit();
			} 
			catch(x_exception e)		{_AddError(e);}
			catch(System.Exception e) 	{_AddError(e);}
			return(Result);
		}
		
		#endregion

	}
}
